package impl

import (
	"context"

	"gitee.com/go-course/go9/projects/devcloud/mcenter/apps/endpoint"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 注册服务的功能列表
func (i *impl) RegistryEndpoint(ctx context.Context, in *endpoint.RegistryRequest) (
	*endpoint.EndpointSet, error) {
	set := endpoint.NewEndpiontSet()
	// 功能列表可以
	opt := &options.UpdateOptions{}
	opt.SetUpsert(true)
	for m := range in.Items {
		r := in.Items[m]
		ep := endpoint.New(r)
		// mongo upsert, insert if primary not exit, or update the record
		_, err := i.col.UpdateOne(ctx,
			bson.M{"_id": ep.Meta.Id},
			bson.M{"$set": ep},
			opt,
		)
		if err != nil {
			return nil, err
		}
		set.Items = append(set.Items, ep)
	}
	return set, nil
}

// 查询功能列表
func (i *impl) QueryEnpoint(ctx context.Context, in *endpoint.QueryEnpointRequest) (
	*endpoint.EndpointSet, error) {
	set := endpoint.NewEndpiontSet()

	// 构造查询条件
	filter := bson.M{}

	opts := &options.FindOptions{}
	opts.SetLimit(int64(in.Page.PageSize))
	opts.SetSkip(in.Page.ComputeOffset())

	cursor, err := i.col.Find(ctx, filter, opts)
	if err != nil {
		return nil, err
	}

	// 执行查询SQL
	for cursor.Next(ctx) {
		ins := endpoint.NewDefaultEndpoint()
		if err := cursor.Decode(ins); err != nil {
			return nil, err
		}
		set.Add(ins)
	}

	// 统计总数
	set.Total, err = i.col.CountDocuments(ctx, filter)
	if err != nil {
		return nil, err
	}
	return set, nil
}
